<?php
# file that will process and save to database new user

# include of site functions
include_once $_SERVER["DOCUMENT_ROOT"].'Meet-n-go/php/includes.php'; 	// contains includes of all files with functions
session_start();					// starts session for current user
c_db_connect(); 					// connect to database

# make sure all data was entered

if(!isset($_POST['name']) || empty($_POST['name'])) i_set_msg_err('Empty name');
else{
	$name = c_escape($_POST['name']); // escape before doing something with it
	
	# check that there are no such name
	$query = "SELECT name FROM groups WHERE name='$name'";
	$result = c_db_query($query);
	$nr_rows = mysql_num_rows($result);
	if($nr_rows != 0) i_set_msg_err('This group name is already registered');
}

if(!isset($_POST['description']) || empty($_POST['description'])) $desc = ''; // empty description
else{
	$desc = c_escape($_POST['description']); // escape before doing something with it
}

$type = c_escape($_POST['type']); // escape before doing something with it

$master = $_SESSION['user_id'];

if( !has_errors() ){
	
	$query = "INSERT INTO groups (`NAME`, `DESC`, `TYPE`, `MASTER`) VALUES ('$name', '$desc', '$type', '$master')";
	if(!c_db_query($query)) i_set_msg_inf('New group not created'); // problem with database
	
	$query = "SELECT id FROM groups WHERE name='$name'";
	$result = c_db_query($query);
	
	if($result){
		$row = mysql_fetch_array($result);
		$groupID = $row[0];
	}
	else i_set_msg_err('Error in group creation');
	
	$user_id = $_SESSION['user_id'];
	$status = '1'; // always registered
	
	$query = "INSERT INTO participants (`USER_ID`, `GROUP_ID`, `STATUS`) VALUES ('$user_id', '$groupID', '$status')";
	if(!c_db_query($query)) i_set_msg_inf('New you are not assigned to group'); // problem with database
	
}

c_db_disconnect(); 					// disconnect from database

# Where to go after processing
if( has_errors() ) 	$page_id = I_CREATE_GROUP; // if there are erros, go back to group creation page
else 				$page_id = I_GROUP_OVERVIEW . '&grp=' . $groupID; // if there are no erros, go to group overview


# code that makes sure, this page is being redirected from afterwards
echo '<head><meta http-equiv="refresh" content="0; url=../../../index.php?id=' . $page_id . '" /></head>';


?>